package com.project.web.wechat.controller.app;

import com.project.common.core.utils.JacksonUtil;
import com.project.common.core.utils.weChat.WeChatUtil;
import com.project.common.core.utils.wx.ReqMessageUtil;
import com.project.common.core.utils.wx.message.res.BaseMessage;
import com.project.common.core.utils.wx.pojo.WeChat;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 微信回调控制器
 *
 * @Author: wyy
 * @Date: 2020-04-08 13:00
 */
@ApiIgnore
@RestController("weChatController")
@RequestMapping("/weChat/anon")
public class WeChatController {
    public static final Logger log = LoggerFactory.getLogger(WeChatController.class);

    /**
     * 验证微信签名【公众号】
     *
     * @param weChat
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/weChat", method = RequestMethod.GET)
    public String validate(WeChat weChat) {
        return WeChatUtil.checkSign(weChat) ? weChat.getEchostr() : "";
    }

    /**
     * 处理微信请求【公众号】
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/weChat", method = RequestMethod.POST)
    public void weChat(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter writer = null;
        try {
            //调用核心业务接受、处理消息
            Map<String, String> map = ReqMessageUtil.parseXml(request);
            log.info("\r\n *********** 接收到的微信消息内容如下 *************** \r\n");
            log.info(JacksonUtil.toJsonStr(map));

            // 初始化基础消息对象
            BaseMessage baseMessage = new BaseMessage();
            baseMessage.setFromUserName(map.get("FromUserName"));
            baseMessage.setToUserName(map.get("ToUserName"));

            //消息类型
            String msgType = map.get("MsgType");
            String responseMsg = "";
            if (msgType.equals(ReqMessageUtil.MESSAGE_TYPE_TEXT)) {
                //文本消息
                log.info("\r\n ******* 微信回调接口中收到的文本：{}", map.get("Content"));
//                responseMsg = wxReplayService.getReplay(map.get("Content"), map);
                log.info("响应消息：" + responseMsg);
            } else if (msgType.equals(ReqMessageUtil.MESSAGE_TYPE_IMAGE)) {//图片消息
            } else if (msgType.equals(ReqMessageUtil.MESSAGE_TYPE_LOCATION)) {//地理位置消息
                String latitude = map.get("Latitude");
                String longitude = map.get("Longitude");
            } else if (msgType.equals(ReqMessageUtil.MESSAGE_TYPE_LINK)) {//链接消息

            } else if (msgType.equals(ReqMessageUtil.MESSAGE_TYPE_VOICE)) {//音频消息

            } else if (msgType.equals(ReqMessageUtil.MESSAGE_TYPE_EVENT)) {//事件消息
                String eventType = map.get("Event");
                if (eventType.equals(ReqMessageUtil.EVENT_TYPE_SUBSCRIBE)) {//关注事件
//                    responseMsg = memberService.saveBySubscribe(map, IpUtils.getIpAddr(request));
                } else if (eventType.equals(ReqMessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {//取消关注事件
//                    weChatUserService.updateByUnSubscribe(map);
                } else if (eventType.equals(ReqMessageUtil.EVENT_TYPE_CLICK)) {//自定义菜单事件
                    String eventKey = map.get("EventKey");
                    log.info("\r\n *****************自定义菜单事件key:{}", eventKey);
//                    responseMsg = wxMenuService.getMessageForWeChatClick(eventKey, baseMessage);
                    log.info("\r\n ***************** 自定义菜单事件被动回复:{}", responseMsg);
                } else if (eventType.equals(ReqMessageUtil.SCANCODE_PUSH)) { //扫码推事件
                }
            } else {
//                TextMessage textMessage = new TextMessage();
//                textMessage.setFromUserName(map.get("ToUserName"));
//                textMessage.setToUserName(map.get("FromUserName"));
//                textMessage.setCreateTime(System.currentTimeMillis());
//                textMessage.setMsgType(ResMessageUtil.MESSAGE_TYPE_TEXT);
//                textMessage.setContent("您好，自动回复暂只支持文本、图文消息!");
//                textMessage.setFuncFlag(0);
//                responseMsg = ResMessageUtil.textMessageToXml(textMessage);
            }

            //响应消息
            writer = response.getWriter();
            writer.write(responseMsg);
        } catch (Exception e) {
            e.printStackTrace();
            IOUtils.closeQuietly(writer);
        }
    }
}
